#! /usr/local/bin/ruby -w
#  autosnippet.rb
#  
#  Copyright 2013 Daniel Mazuera <dmc0113@gmail.com>
def printUsage()
	puts "Usage: autosnippet.rb (valid file) [(valid directory)]"
end

def writetofile(func, var,dir)
	Dir.chdir(dir)
	content = "<snippet>\n<content>\n<![CDATA[#{func}#{var}]]>\n</content>\n<tabTrigger>#{func}</tabTrigger>\n<scope>source.smallbasic</scope>\n</snippet>"
	a = File.new(func+".sublime-snippet","w+")
	puts("writing #{content}  to file #{a}")
	a.syswrite(content)
	a.close()
	puts("closed file")
end

def transform(array)
rstring = "("
array.each_index{
	|x|
	rstring += "\$\{#{x}:#{array[x]}\}, "
	puts("rstring is at #{rstring}")
	}
	rstring.chomp!(", ")
	rstring += ")"
	puts("returning rstring as #{rstring}")
	return rstring
end

def createFiles(file, directory)
	puts("status of #{file} and #{directory}: (#{File.exists?(file) and Dir.exists?(directory)})")
	if not(File.exists?(file) and Dir.exists?(directory)) then
		puts("doing he case loop")
		case ARGV.size
			when 1
				puts "#{file} doesn't appear to be a valid file. Make sure the file exists and that you have read/write access to it and its location"
			when 2
				puts "#{file} and/or #{directory} don't appear to be valid. Make sure they exist and that you have read/write access to their location"
			else
				puts "THERES SOME SERIOUS WITCHCRAFT GOING ON FOR YOU TO BE ABLE TO SEE THIS"
		end
	else
		puts("doing the readline loop")
		IO.foreach(file){|x| function = x[/(([\w.]+)|(\(\))|\(([\w,\s]+)\))+/i,2]
			puts("got func #{function}")
			variables = (x[/(([\w.]+)|(\(\))|\(([\w,\s]+)\))+/i,4] or x[/(([\w.]+)|(\(\))|\(([\w,\s]+)\))+/i,3])
			puts("var is #{variables} and  is equal to () : #{(variables <=> "()") == 0}")
			if (variables <=> "()") == 0 then
				puts("variables is ()")
				writetofile(function,"()",directory)
			else
				if variables then
					puts("splitting variables")
					variables = transform(variables.split(", "))
					writetofile(function,variables,directory)
				else
					puts("passed nil as variable")
					writetofile(function,nil,directory)
				end
			end
		}
	end
end

case ARGV.size
	when 1
		puts("using current working directory")
		createFiles(ARGV[0], Dir.pwd)
	when 2
		puts("using directory #{ARGV[1]}")
		createFiles(ARGV[0], ARGV[1])
	else
		printUsage()
end
